/**
 * <code>HttpServletUtil.java</code>        2012-03-10
 * 
 * Copyright (c) 2008-2012 www.3yx.com all rights reserved.
 */
package com.jf.cloud.service.sysmanager.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;


/**
 * HttpServlet 工具类
 * 
 * @author 程伟平 创建时间：2012-03-10 16:11:55
 */
public final class HttpServletUtil {

	/**
	 * 日志
	 */
	private static final Log log = LogFactory.getLog(HttpServletUtil.class);
	
	/**
	 * URL参数编码
	 * 
	 * @author 程伟平 创建时间：2013-04-09 15:06:55
	 */
	public static String encodeURL(String paramValue, String charset) {
		try {
			if (paramValue != null && paramValue.length() > 0) {
				return URLEncoder.encode(paramValue, charset);
			}
		} catch (UnsupportedEncodingException e) {
			log.error("URL参数编码出错！", e);
		}
		return paramValue;
	}

	/**
	 * URL参数解码
	 * 
	 * @author 程伟平 创建时间：2013-04-09 15:06:55
	 */
	public static String decodeURL(String paramValue, String charset) {
		try {
			if (paramValue != null && paramValue.length() > 0) {
				return URLDecoder.decode(paramValue, charset);
			}
		} catch (UnsupportedEncodingException e) {
			log.error("URL参数解码出错！", e);
		}
		return paramValue;
	}

	/**
	 * 获取URL
	 * 
	 * @author 程伟平 创建时间：2012-03-10 16:07:29
	 * @param request HTTP请求
	 * @return URL
	 */
	public static String getURL(HttpServletRequest request) {
		StringBuffer sb = new StringBuffer();
		String url = request.getRequestURI();

		int lastSlashIndex = url.lastIndexOf("/");
		sb.append(url.substring(lastSlashIndex + 1));

		String method = request.getParameter("method");
		if (method != null && method.length() > 0) {
			sb.append("?method=");
			sb.append(method);
		}
		return sb.toString();
	}

	/**
	 * 获取 真实的IP TODO
	 * 
	 * @author ouyang 创建时间：Apr 16, 2012 3:37:46 PM
	 */
	public static String getIp(HttpServletRequest request) {
		String ip = getRealStr(request.getHeader("X-Forwarded-For"));
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = getRealStr(request.getHeader("Proxy-Client-IP"));
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = getRealStr(request.getHeader("WL-Proxy-Client-IP"));
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = getRealStr(request.getHeader("HTTP_CLIENT_IP"));
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = getRealStr(request.getHeader("HTTP_X_FORWARDED_FOR"));
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = getRealStr(request.getRemoteAddr());
		}
		return ip;
	}
	
	static String getRealStr (String resource){
		return resource!=null&&resource.length()>0?resource.trim():resource; 
	}
	
	/**
	 * 设置请求字符集编码
	 * 
	 * @author 程伟平 创建时间：2012-05-31 10:40:43
	 * @param request
	 */
	public static void setCharacterEncoding(HttpServletRequest request, String encoding) {
		try {
			request.setCharacterEncoding(encoding);
		} catch (UnsupportedEncodingException e) {
			log.error("设置请求字符集编码出错！", e);
		}
	}

	/**
	 * 设置请求字符集编码
	 * 
	 * @author 程伟平 创建时间：2012-05-31 10:40:43
	 * @param request
	 */
	public static void setCharacterEncoding(HttpServletRequest request) {
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			log.error("设置请求字符集编码出错！", e);
		}
	}

	/**
	 * 写入响应字符串
	 * 
	 * @author 程伟平 创建时间：2012-05-31 10:21:46
	 */
	public static void write(HttpServletResponse response, String str) {
		PrintWriter pw = null;
		try {
			response.setContentType("text/html;charset=utf-8");
			pw = response.getWriter();
			pw.write(str);
		} catch (IOException e) {
			log.error("写入响应字符串出错！", e);
		} finally {
			if (pw != null) {
				pw.flush();
				pw.close();
			}
		}
	}
	
	/**
	 * 获取绝对路径
	 * 
	 * @author 程伟平 创建时间：2013-02-25 10:20:30
	 */
	public static String getRealPath(HttpServletRequest request) {
		return request.getSession().getServletContext().getRealPath("/");
	}
	
	/**
	 * 获取绝对路径
	 * 
	 * @author 程伟平 创建时间：2013-02-25 10:20:30
	 */
	public static String getExcelPath(HttpServletRequest request) {
		return getRealPath(request) + PropertiesUtil.getGlobalData().getProperty("excel.path");
	}
	
	/**
	 * 写入响应Excel文件
	 * 
	 * @author 程伟平 创建时间：2013-04-13 10:21:46
	 */
	public static void writeExcel(HttpServletResponse response, String fileName, HSSFWorkbook workbook) {
		try {
			log.info("开始写入响应【" + fileName + "】");
			
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso8859-1") + ".xls");
			HSSFExcelUtil.write(workbook, response.getOutputStream());
			
			log.info("结束写入响应【" + fileName + "】");
		} catch (IOException e) {
			log.error("写入响应Excel文件出错！", e);
		}
	}
}
